package com.ltsznh.android.familybooks.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * Created by Administrator on 13-8-27.
 */
public class dbo {

    public static SQLiteDatabase fbSQLite = null;
    public static String fbSQLiteName = "FamilyBooks";
    protected static SQLiteHelper fbDbHelper;

    protected static final int DB_VERSION = 2;

    protected static Context ctx = null;

    public static void initDatabase(Context context){
        ctx = context;
        fbDbHelper = new SQLiteHelper(ctx,fbSQLiteName,null,DB_VERSION);
        fbSQLite = fbDbHelper.getWritableDatabase();
        Log.d(context.getClass().getName().toString(), dbo.fbSQLite.getPath());
        dbo.fbSQLite.close();
    }

    public static long insertData(Context context,String table,String nullColumnHack,ContentValues values){
        getWritableDatabase(context);
        long i = fbSQLite.insert(table,nullColumnHack,values);
        closeDatabase();
        return i;
    }

    public static int updateData(Context context,String table,ContentValues values,String whereClause,String[] whereArgs){
        getWritableDatabase(context);
        int i = fbSQLite.update(table,values,whereClause,whereArgs);
        closeDatabase();
        return i;
    }

//    protected static Cursor rawQueryData(Context context,String sql,String[] selectionArgs){
//        getReadableDatabase(context);
//        Cursor cursor = fbSQLite.rawQuery(sql,selectionArgs);
//        closeDatabase();
//        return cursor;
//    }

    public static void getWritableDatabase(Context context){
        if(fbSQLite==null || !fbSQLite.isOpen()){
            fbSQLite = fbDbHelper.getWritableDatabase();
        }else if(fbSQLite.isOpen() && fbSQLite.isReadOnly()){
            closeDatabase();
            fbSQLite = fbDbHelper.getWritableDatabase();
        }
    }

    public static void getReadableDatabase(Context context){
        if(fbSQLite==null || !fbSQLite.isOpen()){
            fbSQLite = fbDbHelper.getReadableDatabase();
        }
    }

//    public static void openDatabase1(Context context){
//        if(fbSQLite==null || !fbSQLite.isOpen()){
//            fbSQLite = context.openOrCreateDatabase(fbSQLiteName,Context.MODE_PRIVATE, null);
//        }
//    }

    public static void closeDatabase(){
        if(fbSQLite!=null && fbSQLite.isOpen()){
            fbSQLite.close();
        }
    }


//    public static boolean exeSQL(Context context,String sql){
//        openDatabase1(context);
//        fbSQLite.execSQL(sql);
//        closeDatabase();
//        return true;
//    }

}
